package com.shire.web.console.controller.kf;

import com.alibaba.fastjson.JSONObject;
import com.shire.web.console.common.MD5Util;
import com.shire.web.console.common.RandomGen;
import com.shire.web.console.common.Response;
import com.shire.web.console.dao.device.DeviceKeyDao;
import com.shire.web.console.dao.user.SystemUserDao;
import com.shire.web.console.model.device.DeviceKey;
import com.shire.web.console.model.device.DeviceKeyExample;
import com.shire.web.console.model.user.SystemUser;
import com.shire.web.console.model.user.SystemUserExample;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @Resource
    private SystemUserDao systemUserDao;
    @Resource
    private DeviceKeyDao deviceKeyDao;

    @GetMapping("/manage")
    public ModelAndView manageAdmin(HttpSession session){
        SystemUser curUser = (SystemUser) session.getAttribute("user");
        if (curUser==null)
            return new ModelAndView("redirect:/login");
        ModelAndView ma = new ModelAndView("admin/list");
//        ma.addObject("users",userService.getKfUsers(curUser.getId()));
        return ma;
    }


    @GetMapping("/detail")
    public ModelAndView detail(Integer userId, HttpSession session) {
        if (session.getAttribute("user") == null)
            return new ModelAndView("redirect:/login");
        ModelAndView ma = new ModelAndView("admin/detail");
        SystemUser user = systemUserDao.selectByPrimaryKey(userId);

        ma.addObject("user", user);
        return ma;
    }


    @RequestMapping("/list")
    @ResponseBody
    public Response listAdmin(HttpSession session){
        Response response = new Response();

        try {
            SystemUser user = (SystemUser) session.getAttribute("user");
            if (user==null){
                response.error("请登录");
                return response;
            }
            SystemUserExample example = new SystemUserExample();
            example.createCriteria().andIsKfEqualTo(0).andOpUserIdEqualTo(user.getId());
            example.setOrderByClause("id desc");
            response.setData(systemUserDao.selectByExample(example));
            response.success("操作成功");
        }catch (Exception e){
            response.error("接口错误: "+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public Response resetPwd(@RequestBody SystemUser systemUser, HttpSession session){
        Response response = new Response();

        try {
            if (session.getAttribute("user")==null){
                response.error("请登录");
                return response;
            }
            String pwd = MD5Util.MD5Encode(systemUser.getUserName()+"ABC");
            systemUser.setPassword(pwd);
            systemUserDao.updateByPrimaryKeySelective(systemUser);
            response.success("操作成功");
        }catch (Exception e){
            response.error("接口错误: "+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Response update(@RequestBody SystemUser systemUser, HttpSession session){
        Response response = new Response();
        try {
            SystemUser user = (SystemUser) session.getAttribute("user");

            if (user==null){
                response.error("请登录");
                return response;
            }
            if (systemUser.getStatus() == null)
                systemUser.setStatus(0);
            systemUser.setOpUserId(user.getId());
            systemUserDao.updateByPrimaryKeySelective(systemUser);
            response.success("操作成功");
        }catch (Exception e){
            response.error("接口错误: "+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @PostMapping("/addAccount")
    @ResponseBody
    public Response addAccount(@RequestBody JSONObject systemUser, HttpSession session){
        Response response = new Response();
        try{
            SystemUser curUser = (SystemUser) session.getAttribute("user");
            if (curUser==null){
                response.error("请登录");
                return response;
            }
            SystemUser user = new SystemUser();
            user.setOpUserId(curUser.getId());
            user.setIsKf(0);
            user.setPassword(MD5Util.MD5Encode(systemUser.getString("accountName")+"ABC"));
            user.setUserName(systemUser.getString("accountName"));
            user.setCompanyName(systemUser.getString("companyName"));
            user.setCreateTime(new Date());
            user.setStatus(0);


            Calendar calendar = GregorianCalendar.getInstance();
            String expire = systemUser.getString("expire");
            if (expire.equals("trial")){
                calendar.add(Calendar.DATE, 3);
            }else if (expire.equals("half")){
                calendar.add(Calendar.DATE, 30*4 + 31*2);
            }else if (expire.equals("year")){
                calendar.add(Calendar.DATE, 365);
            }

            user.setExpireDate(calendar.getTime());

            systemUserDao.insertSelective(user);



            List<DeviceKey> deviceKeys = new ArrayList<>();
            for (int i =0 ; i< systemUser.getInteger("wxCount"); i++){
                DeviceKey key = new DeviceKey();
                key.setCompanyId(user.getId());
                key.setCreateTime(new Date());
                key.setExpireDate(calendar.getTime());
                key.setStatus(0);
                key.setDeviceKey(RandomGen.getRandomLowerCase(8));
//                deviceKeyDao.insertSelective(key);
                deviceKeys.add(key);
            }

            deviceKeyDao.batchInsertSelective(deviceKeys);

            response.success("操作成功");

        }catch (Exception e){
            e.printStackTrace();
            response.error("发生错误："+e.getMessage());
        }
        return response;
    }
}
